package com.wlz.security.jdbc.config;

import com.wlz.security.jdbc.handler.MyAuthenticationFailureHandler;
import com.wlz.security.jdbc.handler.MyAuthenticationSuccessHandler;
import com.wlz.security.jdbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 *  1. 增加 rememberMe
 *
 * @author wlz
 */
//@Configuration
public class WebSecurityConfig3 extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置UserDetailsService的实现类
        auth.userDetailsService(userService);

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin() //表单提交
           //.usernameParameter("username1212")  //自定义username入参,必须和表单name值一致
           //.passwordParameter("password1212")
            .loginPage("/login.html") //自定义登录页面
            .loginProcessingUrl("/user/login")  //登录访问路径，必须和表单提交接口一样
            .successForwardUrl("/main")   //认证成功之后转发的路径,必须是Post请求
            .successHandler(new MyAuthenticationSuccessHandler("/main.html"))
//            .failureForwardUrl("/toerror")  //认证失败之后转发的路径,必须是Post请求
            .failureHandler(new MyAuthenticationFailureHandler("/error.html"))
            //授权
            .and().authorizeRequests()
            //设置哪些路径可以直接访问，不需要认证
            .antMatchers("/user/login","/login.html","/error.html").permitAll()
            .anyRequest().authenticated()  //需要认证
            .and().csrf().disable(); //关闭csrf防护

        //记住我
        http.rememberMe()
             .tokenRepository(persistentTokenRepository())//设置数据源
             .tokenValiditySeconds(3600) //超时时间  默认2周
             .userDetailsService(userService);  //设置自定义登录逻辑


    }


    /**
     *  rememberMe 配置
     */
    @Autowired
    public DataSource dataSource;

    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        //设置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }


}
